package com.joysuch.wwyt.core.service.impl;

import com.joysuch.wwyt.core.bean.*;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.entity.BaseEvaluationIndicators;
import com.joysuch.wwyt.core.entity.BaseEvaluationIndicatorsContent;
import com.joysuch.wwyt.core.entity.BaseEvaluationIndicatorsContentDetail;
import com.joysuch.wwyt.core.entity.dsl.QBaseEvaluationIndicatorsContent;
import com.joysuch.wwyt.core.repository.BaseEvaluationIndicatorsContentDao;
import com.joysuch.wwyt.core.repository.BaseEvaluationIndicatorsContentDetailDao;
import com.joysuch.wwyt.core.repository.BaseEvaluationIndicatorsDao;
import com.joysuch.wwyt.core.service.BaseEvaluationIndicatorsService;
import com.joysuch.wwyt.core.support.Context;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.bean.BaseEvaluationContentBean.SearchBaseEvaluationContentConfig;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class BaseEvalutionIndicatorsServiceImpl implements BaseEvaluationIndicatorsService {

    @Autowired
    private BaseEvaluationIndicatorsDao baseEvaluationIndicatorsDao;
    @Autowired
    private BaseEvaluationIndicatorsContentDao baseEvaluationIndicatorsContentDao;
    @Autowired
    private BaseEvaluationIndicatorsContentDetailDao baseEvaluationIndicatorsContentDetailDao;

    /**
     * 新增
     *
     * @param bean
     * @return
     */
    @Override
    @Transactional
    public BaseEvaluationIndicatorsBean add(BaseEvaluationIndicatorsBean bean) {
        //保存评估指标表
        String companyCode = Context.getCompanyCode();
        Long id = Context.getCurrentTenantId();
        String code = Context.getCurrentOrgCode();
        Long eId = baseEvaluationIndicatorsDao.findIdByName(bean.getName());
        if (eId != null) {
            throw new IllegalArgumentException("评估指标表已存在");
        }
        //保存评估指标表
        BaseEvaluationIndicators baseEvaluationIndicators = null;
        BaseEvaluationIndicators save = null;
        try {
            baseEvaluationIndicators = new BaseEvaluationIndicators();
            baseEvaluationIndicators.setName(bean.getName());
            baseEvaluationIndicators.setFormula(bean.getFormula());
            baseEvaluationIndicators.setSignificantRiskScore(bean.getSignificantRiskScore());
            baseEvaluationIndicators.setHigherRiskScore(bean.getHigherRiskScore());
            baseEvaluationIndicators.setGeneralRiskScore(bean.getGeneralRiskScore());
            baseEvaluationIndicators.setLowRiskScore(bean.getLowRiskScore());
            save = baseEvaluationIndicatorsDao.save(baseEvaluationIndicators);
        } catch (Exception e) {
            log.error("新增评估指标表失败",e);
        }
        List<BaseEvaluationContentBean> eicList = bean.getEicList();
        //向前端返回id
        BaseEvaluationIndicatorsBean eiBean = new BaseEvaluationIndicatorsBean();
        eiBean.setId(save.getId());
        List<BaseEvaluationContentBean> eList = new ArrayList<>();
        //保存评估内容表
        for (BaseEvaluationContentBean bic : eicList) {
            Long ecId = baseEvaluationIndicatorsContentDao.findByCodeAndEid(bic.getCode(), baseEvaluationIndicators.getId());
            if (ecId != null) {
                throw new IllegalArgumentException("评估内容已存在");
            }
            try {
                BaseEvaluationIndicatorsContent content = new BaseEvaluationIndicatorsContent();
                content.setName(bic.getName());
                content.setCode(bic.getCode());
                Long id1 = save.getId();
                content.setEiId(save.getId());
                BaseEvaluationIndicatorsContent save1 = baseEvaluationIndicatorsContentDao.save(content);
                BaseEvaluationContentBean bcBean = new BaseEvaluationContentBean();
                bcBean.setId(save1.getId());
                eList.add(bcBean);
            } catch (Exception e) {
               log.error("新增评估内容内容失败",e);
            }
        }
        eiBean.setEicList(eList);
        return eiBean;
    }


    /**
     * 修改
     *
     * @param bean
     * @return
     */
    @Override
    @Transactional
    public BaseEvaluationIndicatorsBean update(BaseEvaluationIndicatorsBean bean) {
        //保存评估指标表
        if (bean.getId() == null) {
            throw new IllegalArgumentException("评估指标表不存在");
        }
        BaseEvaluationIndicators baseEvaluationIndicators = baseEvaluationIndicatorsDao.findById(bean.getId()).get();
        baseEvaluationIndicators.setId(bean.getId());
        baseEvaluationIndicators.setName(bean.getName());
        baseEvaluationIndicators.setFormula(bean.getFormula());
        baseEvaluationIndicators.setSignificantRiskScore(bean.getSignificantRiskScore());
        baseEvaluationIndicators.setHigherRiskScore(bean.getHigherRiskScore());
        baseEvaluationIndicators.setGeneralRiskScore(bean.getGeneralRiskScore());
        baseEvaluationIndicators.setLowRiskScore(bean.getLowRiskScore());
        BaseEvaluationIndicators save = baseEvaluationIndicatorsDao.save(baseEvaluationIndicators);
        List<BaseEvaluationContentBean> eicList = bean.getEicList();
        //向前端返回id
        BaseEvaluationIndicatorsBean eiBean = new BaseEvaluationIndicatorsBean();
        eiBean.setId(save.getId());
        List<BaseEvaluationContentBean> eList = new ArrayList<>();
        //保存评估内容表
        for (BaseEvaluationContentBean bic : eicList) {
            BaseEvaluationContentBean bcBean = new BaseEvaluationContentBean();
            //Long ecId = baseEvaluationIndicatorsContentDao.findByCodeAndEid(bic.getCode(), baseEvaluationIndicators.getId());
            //修改时,若添加评估内容曾新增内容,否则修改
            if (bic.getId() == null) {
                BaseEvaluationIndicatorsContent content = new BaseEvaluationIndicatorsContent();
                content.setCode(bic.getCode());
                content.setEiId(bic.getEiId());
                content.setName(bic.getName());
                content.setOrgCode(Context.getCurrentOrgCode());
                content.setTenentId(Context.getCurrentTenantId());
                BaseEvaluationIndicatorsContent save1 = baseEvaluationIndicatorsContentDao.save(content);
                bcBean.setId(save1.getId());
                eList.add(bcBean);
            }else{
                BaseEvaluationIndicatorsContent content = baseEvaluationIndicatorsContentDao.findById(bic.getId()).get();
                content.setId(bic.getId());
                content.setName(bic.getName());
                content.setCode(bic.getCode());
                content.setEiId(save.getId());
                content.setTenentId(Context.getCurrentTenantId());
                content.setOrgCode(Context.getCurrentOrgCode());
                BaseEvaluationIndicatorsContent save1 = baseEvaluationIndicatorsContentDao.save(content);
                bcBean.setId(save1.getId());
                eList.add(bcBean);
            }
        }
        eiBean.setEicList(eList);
        return eiBean;
    }

    /**
     * 列表查看
     *
     * @return
     */
    @Override
    public List<BaseEvaluationIndicators> findList() {
        return baseEvaluationIndicatorsDao.findAll();
    }

    /**
     * 增加详情表
     *
     * @param bean
     * @return
     */
    @Override
    public List<BaseEvaluationIndicatorsContentDetail> addDetail(AddBaseEvaluationDetailBean bean) {
        List<BaseEvaluationDetailBean> list = bean.getList();
        List<BaseEvaluationIndicatorsContentDetail> edList = new ArrayList<>();
        for (BaseEvaluationDetailBean edBean : list) {
            Long edId = baseEvaluationIndicatorsContentDetailDao.findByCodeAndEicId(edBean.getCode(), edBean.getEicId());
            if (edId != null) {
                throw new IllegalArgumentException("评估指标详情表已存在");
            }
            BaseEvaluationIndicatorsContentDetail eicd = null;
            try {
                eicd = new BaseEvaluationIndicatorsContentDetail();
                eicd.setId(edBean.getId());
                eicd.setCode(String.valueOf(edBean.getScore()));
                eicd.setScore(edBean.getScore());
                eicd.setValue(edBean.getValue());
                eicd.setOptionType(edBean.getOptionType());
                eicd.setEicId(edBean.getEicId());
                eicd.setTenentId(Context.getCurrentTenantId());
                eicd.setOrgCode(Context.getCurrentOrgCode());
                baseEvaluationIndicatorsContentDetailDao.save(eicd);
            } catch (Exception e) {
                log.error("新增评估详情表失败",e);
            }
            edList.add(eicd);
        }
        return edList;
    }


    /**
     * 修改详情
     *
     * @param bean
     * @return
     */
    @Override
    public List<BaseEvaluationIndicatorsContentDetail> updateDetail(AddBaseEvaluationDetailBean bean) {

        //删除详情
        List<Long> deleteIds = bean.getDeleteIds();
        if (deleteIds.size() > 0) {
            for (Long id : deleteIds)
                this.deleteDetail(id);
        }
        List<BaseEvaluationIndicatorsContentDetail> edList = new ArrayList<>();
        List<BaseEvaluationDetailBean> list = bean.getList();
        for (BaseEvaluationDetailBean edBean : list) {
            if (edBean.getId() == null) {
                BaseEvaluationIndicatorsContentDetail detail = new BaseEvaluationIndicatorsContentDetail();
                detail.setScore(edBean.getScore());
                detail.setValue(edBean.getValue());
                detail.setCode(String.valueOf(edBean.getScore()));
                detail.setEicId(edBean.getEicId());
                detail.setOptionType(edBean.getOptionType());
                detail.setTenentId(Context.getCurrentTenantId());
                detail.setOrgCode(Context.getCurrentOrgCode());
                BaseEvaluationIndicatorsContentDetail save = baseEvaluationIndicatorsContentDetailDao.save(detail);
                edList.add(save);
            }else{
                BaseEvaluationIndicatorsContentDetail eicd = baseEvaluationIndicatorsContentDetailDao.findById(edBean.getId()).get();
                eicd.setId(edBean.getId());
                eicd.setCode(String.valueOf(edBean.getScore()));
                eicd.setScore(edBean.getScore());
                eicd.setValue(edBean.getValue());
                eicd.setOptionType(edBean.getOptionType());
                eicd.setEicId(edBean.getEicId());
                eicd.setTenentId(Context.getCurrentTenantId());
                eicd.setOrgCode(Context.getCurrentOrgCode());
                baseEvaluationIndicatorsContentDetailDao.save(eicd);
                edList.add(eicd);
            }
        }
        return edList;
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public List<BaseEvaluationDetailBean> findDetail(Long id) {
        List<BaseEvaluationIndicatorsContentDetail> byEicIds = baseEvaluationIndicatorsContentDetailDao.findByEicId(id);
        //   List<String> typeList = baseEvaluationIndicatorsContentDao.findTypeByEicId(id);
        List<BaseEvaluationDetailBean> edList = new ArrayList<>();
        for (BaseEvaluationIndicatorsContentDetail eicd : byEicIds) {
            BaseEvaluationDetailBean bean = new BaseEvaluationDetailBean();
            bean.setId(eicd.getId());
            bean.setCode(eicd.getCode());
            bean.setScore(eicd.getScore());
            bean.setValue(eicd.getValue());
            bean.setOptionType(eicd.getOptionType());
            bean.setEicId(eicd.getEicId());
            edList.add(bean);
        }
        return edList;
    }

    /**
     * 获取详情内容
     *
     * @param id
     * @return
     */
   /* @Override
    public List<BaseEvaluationDetailBean> getDetail(Long id) {
        List<String> typeList = baseEvaluationIndicatorsContentDetailDao.findTypeByEicId(id);
        AddEvaluationDetailBean addBean = new AddEvaluationDetailBean();
        AddBaseEvaluationDetailBean abBean = new AddBaseEvaluationDetailBean();
        for (String type : typeList) {
            abBean.setOpyionType(type);
            List<BaseEvaluationIndicatorsContentDetail> cdList = baseEvaluationIndicatorsContentDetailDao.findByEicIdAndType(id, type);
        }
        return null;
    }*/


    /**
     * 查看(评估指标+评估内容)
     *
     * @param id
     * @return
     */
    @Override
    public BaseEvaluationIndicatorsBean find(Long id) {
        Optional<BaseEvaluationIndicators> byId = baseEvaluationIndicatorsDao.findById(id);
        if (!byId.isPresent()) {
            return null;
        }
        BaseEvaluationIndicatorsBean eiBean = new BaseEvaluationIndicatorsBean();
        eiBean.setId(byId.get().getId());
        eiBean.setName(byId.get().getName());
        eiBean.setFormula(byId.get().getFormula());
        eiBean.setSignificantRiskScore(byId.get().getSignificantRiskScore());
        eiBean.setHigherRiskScore(byId.get().getHigherRiskScore());
        eiBean.setGeneralRiskScore(byId.get().getGeneralRiskScore());
        eiBean.setLowRiskScore(byId.get().getLowRiskScore());
        //查询评估内容表
        List<BaseEvaluationIndicatorsContent> eciList = baseEvaluationIndicatorsContentDao.findByEiId(id);
        List<BaseEvaluationContentBean> ecList = new ArrayList<>();
        for (BaseEvaluationIndicatorsContent eic : eciList) {
            BaseEvaluationContentBean bean = new BaseEvaluationContentBean();
            bean.setId(eic.getId());
            bean.setName(eic.getName());
            bean.setCode(eic.getCode());
            bean.setEiId(eic.getEiId());
            ecList.add(bean);
        }
        eiBean.setEicList(ecList);
        return eiBean;
    }

    /**
     * 删除评估指标表
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        List<BaseEvaluationIndicatorsContent> eicList = baseEvaluationIndicatorsContentDao.findByEiId(id);
        for (BaseEvaluationIndicatorsContent eic : eicList) {
            this.deleteContent(eic.getId());
        }
        baseEvaluationIndicatorsDao.deleteById(id);
    }

    /**
     * 删除评估内容表
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteContent(Long id) {
        List<BaseEvaluationIndicatorsContentDetail> eicdList = baseEvaluationIndicatorsContentDetailDao.findByEicId(id);
        for (BaseEvaluationIndicatorsContentDetail eicd : eicdList) {
            this.deleteDetail(eicd.getId());
        }
        baseEvaluationIndicatorsContentDao.deleteById(id);
    }

    /**
     * 删除详情
     *
     * @param id
     */
    @Override
    public void deleteDetail(Long id) {
        baseEvaluationIndicatorsContentDetailDao.deleteById(id);
    }

    /**
     * 分页
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public Page<BaseEvaluationContentBean> findByPage(Pageable page, SearchBaseEvaluationContentConfig condition) {
        Predicate predicate = prepareListSearchCondition(condition);
        Page<BaseEvaluationIndicatorsContent> data = predicate == null ? baseEvaluationIndicatorsContentDao.findAll(page) : baseEvaluationIndicatorsContentDao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data, new PageDataConvert<BaseEvaluationContentBean, BaseEvaluationIndicatorsContent>() {
            @Override
            public BaseEvaluationContentBean convert(BaseEvaluationIndicatorsContent baseConfig) {
                BaseEvaluationContentBean bean = new BaseEvaluationContentBean();
                BeanUtils.copyProperties(baseConfig, bean);
                return bean;
            }
        });
    }


    private Predicate prepareListSearchCondition(SearchBaseEvaluationContentConfig condition) {
        Predicate p = null;
        QBaseEvaluationIndicatorsContent q = QBaseEvaluationIndicatorsContent.BaseEvaluationIndicatorsContent;
        if (condition.getEiId() != null) {
            p = ExpressionUtils.and(p, q.eiId.eq(condition.getEiId()));
        }
        if (condition.getCode() != null) {
            p = ExpressionUtils.and(p, q.code.contains(condition.getCode()));
        }
        if (condition.getName() != null) {
            p = ExpressionUtils.and(p, q.name.contains(condition.getName()));
        }
        return p;
    }


}
